<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think\log\driver;

use app\common\model\trSystemSet;
use app\saas\model\trSetting;
use Qcloud\Cos\Client;
use think\App;

/**
 * 本地化调试输出并存储到腾讯云cos
 */
class File
{
    protected $config = [
        'time_format' => ' c ',
        'single'      => false,
        'file_size'   => 2097152,
        'path'        => '',
        'apart_level' => [],
        'max_files'   => 0,
        'json'        => false,
    ];

    protected $cosConfig;
    protected $cosClientObject;
    protected $app;

    // 实例化并传入参数
    public function __construct(App $app, $config = [])
    {
        $this->app = $app;

        if (is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }

        if(request()->module() == "saas") { // saas端
            $this->cosConfig = trSetting::getFields("secret_id,secret_key,region,bucket");
        }else{
            $this->cosConfig = trSystemSet::getValue("tcConfig");
        }
        if (empty($this->cosConfig["secretId"]) || empty($this->cosConfig["secretKey"]) || empty($this->cosConfig["region"]) || empty($this->cosConfig["bucket"])) {
            throw new \Exception("未配置腾讯云信息，无法使用");
        }
        $this->cosClientObject = new Client([
            'region' => $this->cosConfig["region"], #地域，如ap-guangzhou,ap-beijing-1
            'credentials' => array(
                'secretId' => $this->cosConfig["secretId"],
                'secretKey' => $this->cosConfig["secretKey"],
            ),
        ]);
        if(!empty($_SERVER["TIMER_TRIGGER"])){
            $this->config['path'] = "car_tp5/runtime/timer_log/"; //定时任务 cos存储的目录
        }else {
            $this->config['path'] = "car_tp5/runtime/run_log/"; //cos存储的目录
        }
    }

    /**
     * 日志写入接口
     * @access public
     * @param  array    $log    日志信息
     * @param  bool     $append 是否追加请求信息
     * @return bool
     */
    public function save(array $log = [], $append = false)
    {
        $destination = $this->getMasterLogFile();

        $info = [];

        foreach ($log as $type => $val) {

            foreach ($val as $msg) {
                if (!is_string($msg)) {
                    $msg = var_export($msg, true);
                }

                $info[$type][] = $this->config['json'] ? $msg : '[ ' . $type . ' ] ' . $msg;
            }

            if (!$this->config['json'] && (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level']))) {
                // 独立记录的日志级别
                $path = dirname($destination);
                $filename = $this->getApartLevelFile($path, $type);

                $this->write($info[$type], $filename, true, $append);

                unset($info[$type]);
            }
        }

        if ($info) {
            return $this->write($info, $destination, false, $append);
        }

        return true;
    }

    /**
     * 日志写入
     * @access protected
     * @param  array     $message 日志信息
     * @param  string    $destination 日志文件
     * @param  bool      $apart 是否独立文件写入
     * @param  bool      $append 是否追加请求信息
     * @return bool
     */
    protected function write($message, $destination, $apart = false, $append = false)
    {
        // 检测日志文件大小，超过配置大小则备份日志文件重新生成
        $this->checkLogSize($destination);

        // 日志信息封装
        $info['timestamp'] = date($this->config['time_format']);

        foreach ($message as $type => $msg) {
            $msg = is_array($msg) ? implode("\r\n", $msg) : $msg;
            if (PHP_SAPI == 'cli') {
                $info['msg']  = $msg;
                $info['type'] = $type;
            } else {
                $info[$type] = $msg;
            }
        }

        if (PHP_SAPI == 'cli') {
            $message = $this->parseCliLog($info);
        } else {
            // 添加调试日志
            $this->getDebugLog($info, $append, $apart);

            $message = $this->parseLog($info);
        }

        try {
            $result = $this->cosClientObject->getObject(array(
                'Bucket' => $this->cosConfig["bucket"],
                'Key' => $destination
            ));
        } catch (\Exception $e) {
        }

        if(!empty($result['Body'])){
            $message = $result['Body']->__toString() . $message;
        }
        try {
            $this->cosClientObject->putObject(array(
                'Bucket' => $this->cosConfig["bucket"],
                'Key' => $destination,
                'Body' => $message
            ));
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 获取主日志文件名
     * @access public
     * @return string
     */
    protected function getMasterLogFile()
    {
        if ($this->config['max_files']) {
            $marker = '';
            $isDelete = false;
            while (true) {
                try {
                    $result = $this->cosClientObject->listObjects(array(
                        'Bucket' => $this->cosConfig["bucket"],
                        'Prefix' => $this->config["path"],
                        'Marker' => $marker,
                        'MaxKeys' => 1000
                    ));
                    $marker = $result['NextMarker'];
                    if (!$result['IsTruncated']) {
                        if(count($result["Contents"]) > $this->config["max_files"]){
                            $isDelete = true;
                        }
                        break;
                    }else if(count($result["Contents"]) > $this->config["max_files"]){
                        $isDelete = true;
                        break;
                    }
                } catch (\Exception $e) {
                    throw $e;
                }
            }
            if($isDelete) {
                try {
                    foreach ($result['Contents'] as $rt) {
                        $this->cosClientObject->deleteObject(array(
                            'Bucket' => $this->cosConfig["bucket"],
                            'Key' => $rt['Key']
                        ));
                    }
                } catch (\Exception $e) {
                    throw $e;
                }
            }
        }

        $cli = PHP_SAPI == 'cli' ? '_cli' : '';

        if ($this->config['single']) {
            $name = is_string($this->config['single']) ? $this->config['single'] : 'single';

            $destination = $this->config['path'] . $name . $cli . '.log';
        } else {
            if ($this->config['max_files']) {
                $filename = date('Ymd') . $cli . '.log';
            } else {
                $filename = date('Ym') . "/" . date('d') . $cli . '.log';
            }

            $destination = $this->config['path'] . $filename;
        }

        return $destination;
    }

    /**
     * 获取独立日志文件名
     * @access public
     * @param  string $path 日志目录
     * @param  string $type 日志类型
     * @return string
     */
    protected function getApartLevelFile($path, $type)
    {
        $cli = PHP_SAPI == 'cli' ? '_cli' : '';

        if ($this->config['single']) {
            $name = is_string($this->config['single']) ? $this->config['single'] : 'single';
        } elseif ($this->config['max_files']) {
            $name = date('Ymd');
        } else {
            $name = date('d');
        }

        return $path . "/" . $name . '_' . $type . $cli . '.log';
    }

    /**
     * 检查日志文件大小并自动生成备份文件
     * @access protected
     * @param  string    $destination 日志文件
     * @return void
     */
    protected function checkLogSize($destination)
    {
        try {
            $result = $this->cosClientObject->headObject(array(
                'Bucket' => $this->cosConfig["bucket"],
                'Key' => $destination
            ));
            if (floor($this->config['file_size']) <= $result["ContentLength"]) {
                $this->cosClientObject->copyObject(array(
                    'Bucket' => $this->cosConfig["bucket"],
                    'CopySource' => "{$this->cosConfig["bucket"]}.cos.{$this->cosConfig["region"]}.myqcloud.com/{$destination}",
                    'Key' => dirname($destination) . "/" . time() . '-' . basename($destination),
                ));
                $this->cosClientObject->deleteObject(array(
                        'Bucket' => $this->cosConfig["bucket"],
                        'Key' => $destination
                    )
                );
            }
        } catch (\Exception $e) {
        }
    }

    /**
     * CLI日志解析
     * @access protected
     * @param  array     $info 日志信息
     * @return string
     */
    protected function parseCliLog($info)
    {
        if ($this->config['json']) {
            $message = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
        } else {
            $now = $info['timestamp'];
            unset($info['timestamp']);

            $message = implode("\r\n", $info);

            $message = "[{$now}]" . $message . "\r\n";
        }

        return $message;
    }

    /**
     * 解析日志
     * @access protected
     * @param  array     $info 日志信息
     * @return string
     */
    protected function parseLog($info)
    {
        $requestInfo = [
            'ip'     => $this->app['request']->ip(),
            'method' => $this->app['request']->method(),
            'host'   => $this->app['request']->host(),
            'uri'    => $this->app['request']->url(),
        ];

        if ($this->config['json']) {
            $info = $requestInfo + $info;
            return json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\r\n";
        }

        array_unshift($info, "---------------------------------------------------------------\r\n[{$info['timestamp']}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}");
        unset($info['timestamp']);

        return implode("\r\n", $info) . "\r\n";
    }

    protected function getDebugLog(&$info, $append, $apart)
    {
        if ($this->app->isDebug() && $append) {

            if ($this->config['json']) {
                // 获取基本信息
                $runtime = round(microtime(true) - $this->app->getBeginTime(), 10);
                $reqs    = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';

                $memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2);

                $info = [
                    'runtime' => number_format($runtime, 6) . 's',
                    'reqs'    => $reqs . 'req/s',
                    'memory'  => $memory_use . 'kb',
                    'file'    => count(get_included_files()),
                ] + $info;

            } elseif (!$apart) {
                // 增加额外的调试信息
                $runtime = round(microtime(true) - $this->app->getBeginTime(), 10);
                $reqs    = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';

                $memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2);

                $time_str   = '[运行时间：' . number_format($runtime, 6) . 's] [吞吐率：' . $reqs . 'req/s]';
                $memory_str = ' [内存消耗：' . $memory_use . 'kb]';
                $file_load  = ' [文件加载：' . count(get_included_files()) . ']';

                array_unshift($info, $time_str . $memory_str . $file_load);
            }
        }
    }
}
